import React, {useEffect, useRef, useState} from 'react'
import "./task.less"
import {Button, DatePicker, Form, Input, message, Modal, Popconfirm, Table, Tag} from "antd";
import {addTask, completeTask, getTaskList, removeTask} from "../../api/task"

// 对日期的处理的方法
const formatTime = (time) => {
    let arr = time.match(/\d+/g),
        [, month, day, hours = '00', minutes = '00'] = arr;
    return `${month.padStart(2, 0)}-${day.padStart(2, 0)} ${hours}:${minutes}`
}

const Task = function () {
    /* 表格列的数据 */
    const columns = [
        {
            title: '编号',
            dataIndex: 'id',
            align: 'center',//居中
            width: '8%'
        },
        {
            title: '任务描述',
            dataIndex: 'task',
            ellipsis: true, // 超出隐藏
            align: 'center',//剧中
            width: '50%'
        },
        {
            title: '状态',
            dataIndex: 'state',
            align: 'center',//剧中
            width: '10%',
            render: (text, record) => { // 复杂逻辑渲染
                // text:某个单元格数据
                return text === 2 ? '已完成' : '未完成'
            }
        },
        {
            title: '完成时间',
            dataIndex: 'time',
            align: 'center',//剧中
            width: '15%',
            render: (_, record) => {
                let {state, time, complete} = record
                if (+state === 2) time = complete;
                return formatTime(time)
            }
        },
        {
            title: '操作',
            render: (_, record) => {
                let {state, id} = record
                return <>
                    <Popconfirm
                        title="你确定要删除这个任务?"
                        onConfirm={handleDelete.bind(null, id)}
                    >
                        <Button type="link">删除</Button>
                    </Popconfirm>
                    {state === 1 ? <Popconfirm
                        title="你确定要完成这个任务?"
                        onConfirm={handleUpdate.bind(null, id)}
                    >
                        <Button type="link">完成</Button>
                    </Popconfirm> : null}
                </>
            }
        }
    ]
    const rules = {
        task: [{required: true, message: '任务描述是必填项'}, {min: 6, message: '输入的内容至少6位及以上'}],
        time: [{required: true, message: '预期完成时间是必填项'}]
    }
    /* 定义需要的状态 */
    let [curTag, setCurTag] = useState(0), // 当前标签
        [listData, setListaData] = useState([]),
        [tableLoading, setTableLoading] = useState(false),
        [modelOpen, setModelOpen] = useState(false),
        [confirmLoading, setConfirmLoading] = useState(false),
        [formData, setFormData] = useState({});

    let formRef = useRef(null)
    // let [formRef] = Form.useForm()

    useEffect(() => {
        getlist()
    }, [curTag])

    // 注意
    // const toggleTag = (index) => {
    //     setCurTag(index) //
    //     this.getlist(); // 这里拿到的是上一个上下文的 index，因为这个 getlist 闭包始终在上一个函数作用域中
    //      ==>  解决方法：基于 useEffect 设置状态值的依赖，在依赖项改变再去执行
    // }

    const handleDelete = (id) => {
        removeTask({id}).then(res => {
            if (res.code === 0) {
                getlist();
                message.success('恭喜您，删除成功!');
            } else {
                message.warning('删除失败!');
            }
        })
    }
    const handleUpdate = (id) => {
        completeTask({id}).then(res => {
            if (res.code === 0) {
                getlist();
                message.success('恭喜您，完成成功!');
            } else {
                message.warning('完成失败!');
            }
        })
    }
    // 行点击
    const rowClick = (row) => {
        console.log('单行点击')
    }
    /* 对话框和表单处理 */
    const closeModal = () => {
        setModelOpen(false)
        formRef.current.resetFields();//清空内容
    }
    const submit = () => {// 提交
        setConfirmLoading(true)
        formRef.current.validateFields().then(data => {
            addTask(data).then(res => {
                if (res.code === 0) {
                    closeModal();
                    getlist()
                    setConfirmLoading(false)
                    message.success('恭喜您，当前操作成功!');
                } else {
                    closeModal();
                    message.error('很遗憾，当前操作失败，请稍后再试!');
                }
            })
        })
    }

    const getlist = () => {
        setTableLoading(true)
        let params = {state: curTag}
        getTaskList(params).then(res => {
            if (res.code === 0) {
                let {list} = res
                setListaData(list)
                setTableLoading(false)
            }
        })
    }

    return <div className="task-box">
        <div className="nav-title">
            <h2>TASK OA 任务关系系统 </h2>
            <Button type="primary" size="middle" onClick={() => setModelOpen(true)}>新增任务</Button>
        </div>
        <div className="tag-box">
            {['全部', '未完成', '已完成'].map((item, index) => {
                return <Tag
                    color={curTag === index ? '#1677ff' : ''} key={index}
                    onClick={() => setCurTag(index)}>{item}</Tag>
            })}
        </div>
        {/*表单*/}
        <Table
            rowKey={(record) => record.id}
            dataSource={listData}
            columns={columns}
            loading={tableLoading}
            onRow={row => {
                return {
                    onClick: rowClick.bind(null, row)
                }
            }}
        />
        {/*对话框*/}
        <Modal title='新增任务窗口'
               open={modelOpen}
               confirmLoading={confirmLoading}
               keyboard={false} // esc关闭
               maskClosable={false} // 点击蒙层关闭
               okText="确认提交"
               onCancel={closeModal}
               onOk={submit}
        >
            <Form
                ref={formRef}
                layout='vertical'
                initialValues={formData} // 设置初始值
            >
                <Form.Item label="任务描述" name="task" validateTrigger="onBlur" rules={rules.task}>
                    <Input.TextArea rows={4}></Input.TextArea>
                </Form.Item>
                <Form.Item label="预期完成时间" name="time" rules={rules.time}>
                    <DatePicker/>
                </Form.Item>
            </Form>
        </Modal>
    </div>
}


export default Task
